package com.foreveross.project.usercenterserver.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foreveross.project.usercenterserver.common.utils.ContextUtil;
import com.foreveross.project.usercenterserver.exception.CustomException;
import com.foreveross.project.usercenterserver.oauth2.domain.UcAccount;
import com.foreveross.project.usercenterserver.oauth2.domain.UcApp;
import com.foreveross.project.usercenterserver.oauth2.domain.UcRole;
import com.foreveross.project.usercenterserver.oauth2.domain.UcTenant;
import com.foreveross.project.usercenterserver.oauth2.mapper.UcAccountMapper;
import com.foreveross.project.usercenterserver.oauth2.mapper.UcAppMapper;
import com.foreveross.project.usercenterserver.oauth2.mapper.UcRoleMapper;
import com.foreveross.project.usercenterserver.oauth2.mapper.UcTenantMapper;
import com.foreveross.project.usercenterserver.security.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: yz
 * @Date: 2019/7/22 9:48 AM
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UcAccountMapper ucAccountMapper;

    @Autowired
    private UcRoleMapper ucRoleMapper;

    @Autowired
    private UcTenantMapper ucTenantMapper;

    @Autowired
    private UcAppMapper ucAppMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //TODO
        //这里需要改造，那个客户端的用户登陆？
        HttpServletRequest request = ContextUtil.getRequest();
        String clientId = request.getParameter("client_id");
        String appCode = request.getParameter("app_code");
        UcTenant ucTenant = ucTenantMapper.findByClientId(clientId);
        if (ObjectUtil.isNull(ucTenant)){
            throw new CustomException(username + " not found!");
        }
        QueryWrapper<UcApp> ucAppQueryWrapper = new QueryWrapper<>();
        ucAppQueryWrapper.eq("app_code",appCode);
        ucAppQueryWrapper.eq("tenant_fk_id",ucTenant.getTenantFkId());
        UcApp app = ucAppMapper.selectOne(ucAppQueryWrapper);
        if (ObjectUtil.isNull(app)){
            throw new CustomException(username + " not found!");
        }
        //检查客户端是否存在
        //检查应用是否存在
        //使用client查找对应的用户信息
        QueryWrapper<UcAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("app_fk_id",app.getAppFkId());
        wrapper.eq("tenant_fk_id",ucTenant.getTenantFkId());
        UcAccount user = ucAccountMapper.selectOne(wrapper);
        if (ObjectUtil.isNotNull(user)) {
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            //TODO 这里的权限需要从casbin中获取
            List<UcRole> roles = ucRoleMapper.findUserRoleByUserId(user.getId());
            if (roles.size() > 0) {
                for (UcRole temp : roles) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(temp.getRoleName());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            return new UserInfo(user.getAccountFkId(), user.getUsername(), user.getPassword(),clientId,
                    user.getDelFlag() >= 0, true, true, user.getDelFlag() != -2, grantedAuthorities);

        } else {
            throw new UsernameNotFoundException(username + " not found!");
        }
    }
}
